package ch.fhnw.qualiscan.application.pages;

import java.util.Vector;

import ch.fhnw.qualiscan.Config;
import ch.fhnw.qualiscan.application.models.SurveyModel;
import ch.fhnw.qualiscan.application.models.UserModel;
import ch.fhnw.qualiscan.core.Page;
import ch.fhnw.qualiscan.core.db.fieldfactories.NewUserFieldFactory;
import ch.fhnw.qualiscan.core.db.pojos.SurveyUserRole;
import ch.fhnw.qualiscan.core.db.pojos.User;
import ch.fhnw.qualiscan.core.helpers.EmailHelper;
import ch.fhnw.qualiscan.core.helpers.UserSession;
import ch.fhnw.qualiscan.core.libraries.NotificationLib;

import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.data.util.BeanItem;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Form;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.VerticalLayout;

import eu.livotov.tpt.i18n.TM;

@SuppressWarnings("serial")
public class NewAccount extends Page { 
	
	private Form signUpForm;	
	private SurveyUserRole invitationSurvey = null;
	private SurveyModel surveyModel;
	private UserModel userModel;
	
	@Override
	public void initModelsAndHelpers() {
		userModel = new UserModel();
		surveyModel = new SurveyModel();
	}
	
	@Override
	public void buildLayout() {
		if(sessionHelper.isUserSessionSet()) {
			addComponent(textHelper.h1(TM.get("newaccount.title2")));
			addComponent(textHelper.p(TM.get("newaccount.desc2")));
			
		} else {
			addComponent(textHelper.h1(TM.get("newaccount.title")));
			addComponent(textHelper.p(TM.get("newaccount.desc")));

			bindToSurvey();
			addComponent(buildSignUpForm());
		}
	}
	
	/**
	 * Builds the form for creating a new account.
	 * @return Form
	 */
	public Form buildSignUpForm() {
		final User user;
		boolean isStandalone;
		
		if(invitationSurvey != null) {
			user = userModel.getUserById(invitationSurvey.getUser().getId());
			isStandalone = false;
		} else {
			user = new User();
			isStandalone = true;
		}
		
		signUpForm = new Form();
        
        BeanItem<User> item = new BeanItem<User>(user);
        
        signUpForm.setItemDataSource(item);
        signUpForm.setImmediate(true);
        signUpForm.setFormFieldFactory(new NewUserFieldFactory(isStandalone));
        
        Vector<String> order = new Vector<String>();
        order.add("firstname");
        order.add("lastname");
        order.add("email");
        order.add("password");
        order.add("language");
		
        signUpForm.setVisibleItemProperties(order); 
        
        HorizontalLayout buttonBar = new HorizontalLayout();
        signUpForm.getFooter().addComponent(buttonBar);
        Button commit = new Button(TM.get("action.save"), new ClickListener() {
            public void buttonClick(ClickEvent event) {
            	try {
            		signUpForm.commit();
            		
            		if(invitationSurvey != null) {
            			// send a confirmation mail
            			EmailHelper email = new EmailHelper();
            			email.sendConfirmationMail(user);
            			userModel.updateUser(user);
            		}
            		else {
            			boolean saved = userModel.saveUser(user);
            			if(saved == false) {
            				NotificationLib.showError(TM.get("notification.error.username.exists"), null);
            				return;
            			}
            		}
            		
            		// changing language interface if necessary
            		TM.getDictionary().setDefaultLanguage(user.getLanguage().getLocale());
            		requestRepaintAll();
            		
            		// setting user session
            		UserSession userSession = new UserSession();
            		userSession.setId(user.getId());
            		userSession.setEmail(user.getEmail());
            		userSession.setFirstname(user.getFirstname());
            		userSession.setLastname(user.getLastname());
            		userSession.setLanguage(user.getLanguage());
            		userSession.setRole(user.getRole());
         
            		sessionHelper.setUserSession(userSession);
            		// update components
            		componentLib.userLoggedIn();
            		
            		// redirect
            		urlLib.setPage("Dashboard");
            		
            		// show notifications
            		NotificationLib.showSuccess(TM.get("action.saved"), null);
            	}
            	catch (InvalidValueException e) {
                    return;
            	}
            }
        });
 
        commit.setIcon(Config.ICON_SAVE);
        buttonBar.addComponent(commit);
        
		return signUpForm;
	}
	
	/**
	 * Analyses whether there is a project which needs to be binded to this account. Displays a status.
	 */
	public void bindToSurvey() {
		if(urlLib.getThirdFragment() != null) {
			SurveyUserRole sur = surveyModel.getSurveyUserRoleByHash(urlLib.getThirdFragment());
			if(sur == null) {
				
			} else {
				invitationSurvey = sur;
				VerticalLayout toSurvey = new VerticalLayout();
				toSurvey.addComponent(textHelper.p(TM.get("newaccount.bindsurvey", sur.getSurvey().getTitle())));
				addComponent(toSurvey);
			}
		}
	}
	
	@Override
	public void setNeededPermissions() {
		
	}

	@Override
	public void initComponents() {
		
	}

	@Override
	public void thirdParameterChanged(String thirdParameter) {
		
	}

}
